<template>
  <div>
    <!-- 功能条 -->
    <el-row class="buttonRow">
      <el-col :span="2">
        <el-button type="primary" size="mini" @click="openCreateFormDialog">创建站或柜</el-button>
      </el-col>
      <el-col :span="22">
        <el-input v-model="getStationsReq.keyword" size="mini" :placeholder="searchWord" :disabled="searchDisabled" clearable @keyup.enter.native="search" @clear="clearKeyword">
          <el-button slot="append" icon="el-icon-search" @click="search" />
        </el-input>
      </el-col>
    </el-row>
    <!-- 列表 -->
    <el-collapse v-model="activeNames" :accordion="true" class="collapse" @change="collapseChange">
      <el-collapse-item :title="stationTableTitle" name="stationTable" class="collapseItem" :disabled="stationTableDisable">
        <el-row>
          <div class="tableDiv">
            <el-table :data="stationTableAry" border stripe @expand-change="expandStationTable">
              <el-table-column label="序号" prop="index" width="50px" :show-overflow-tooltip="true" />
              <el-table-column label="详情" width="50px" type="expand">
                <template slot-scope="props">
                  <el-form label-position="left" inline class="table-expand">
                    <el-form-item label="拥有智能柜的数量">
                      <span>{{ props.row.hasChestNum }}</span>
                    </el-form-item>
                    <el-form-item label="开门报警时长">
                      <span>{{ props.row.doorOpenAlertSpan }}</span>
                    </el-form-item>
                    <el-form-item label="自动登出时长">
                      <span>{{ props.row.autoLogoutSpan }}</span>
                    </el-form-item>
                    <el-form-item label="自动上传数据时长">
                      <span>{{ props.row.autoUploadSpan }}</span>
                    </el-form-item>
                    <el-form-item label="自动下载数据时长">
                      <span>{{ props.row.autoDownloadSpan }}</span>
                    </el-form-item>
                    <el-form-item label="Id">
                      <span>{{ props.row.id }}</span>
                    </el-form-item>
                    <el-form-item label="创建时间">
                      <span>{{ props.row.gmtCreate }}</span>
                    </el-form-item>
                    <el-form-item label="更新时间">
                      <span>{{ props.row.gmtModified }}</span>
                    </el-form-item>
                  </el-form>
                </template>
              </el-table-column>
              <el-table-column label="站点编号" prop="stationCode" width="200px" :show-overflow-tooltip="true" />
              <el-table-column label="站点名称" prop="stationName" width="200px" :show-overflow-tooltip="true" />
              <el-table-column label="说明" prop="remark" :show-overflow-tooltip="true" />
              <el-table-column label="设备IP" prop="bindIp" :show-overflow-tooltip="true" />
              <el-table-column label="设备状态" prop="onlineStatus==0" :show-overflow-tooltip="true" :formatter="formatOnlineStatus" />
              <el-table-column label="操作" width="350px">
                <template slot-scope="scope">
                  <template>
                    <el-button type="primary" size="mini" @click="toChestTable(scope.row)">管理智能柜</el-button>
                  </template>
                  <template>
                    <el-button type="primary" size="mini" @click="toUpdate(scope.row)">更新客户端</el-button>
                  </template>
                  <template>
                    <el-button type="warning" size="mini" @click="openEditStationFormDialog(scope.row)">编辑</el-button>
                  </template>
                  <template>
                    <el-button type="danger" size="mini" @click="del(scope.row)">删除</el-button>
                  </template>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-row>
        <el-row type="flex" justify="center" class="pageRow">
          <el-pagination
            :current-page="getStationsReq.currentPage"
            :page-sizes="[10, 25, 50]"
            :page-size="getStationsReq.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="stationTotal"
            @size-change="handleStationSizeChange"
            @current-change="handleStationCurrentChange"
          />
        </el-row>
      </el-collapse-item>
      <el-collapse-item v-if="chestTableTitle!=''" :title="chestTableTitle" name="chestTable" class="collapseItem" :disabled="chestTableDisable">
        <el-row>
          <div class="tableDiv">
            <el-table :data="chestsByStationAry" border stripe @expand-change="expandChestTable">
              <el-table-column label="详情" width="50px" type="expand">
                <template slot-scope="props">
                  <el-form label-position="left" inline class="table-expand">
                    <el-form-item label="具备其使用权的用户">
                      <span>{{ props.row.hasUsers }}</span>
                    </el-form-item>
                    <el-form-item label="所属的智能柜组">
                      <span>{{ props.row.hasChestGroups }}</span>
                    </el-form-item>
                    <el-form-item label="创建时间">
                      <span>{{ props.row.gmtCreate }}</span>
                    </el-form-item>
                    <el-form-item label="更新时间">
                      <span>{{ props.row.gmtModified }}</span>
                    </el-form-item>
                  </el-form>
                </template>
              </el-table-column>
              <el-table-column label="Id" prop="id" width="300px" :show-overflow-tooltip="true" />
              <el-table-column label="柜号" prop="chestNo" :show-overflow-tooltip="true" />
              <el-table-column label="操作" width="430px">
                <template slot-scope="scope">
                  <template>
                    <el-button type="primary" size="mini" @click="setUsers(scope.row)">分配用户</el-button>
                  </template>
                  <template>
                    <el-button type="primary" size="mini" @click="setChestGroups(scope.row)">分配柜组</el-button>
                  </template>
                  <template>
                    <el-button type="primary" size="mini" @click="setStations(scope.row)">分配站点</el-button>
                  </template>
                  <template>
                    <el-button type="warning" size="mini" @click="openEditChestFormDialog(scope.row)">编辑</el-button>
                  </template>
                  <template>
                    <el-button type="danger" size="mini" @click="del(scope.row)">删除</el-button>
                  </template>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-row>
      </el-collapse-item>
    </el-collapse>
    <!-- 表单对话框 -->
    <el-dialog :visible.sync="formDialogVisible" width="80%" top="5vh" :close-on-click-modal="false" :show-close="false">
      <el-row class="formTitleRow">
        <div class="formTitle">{{ formTitle }}</div>
      </el-row>
      <el-divider />
      <el-row class="formRow" :gutter="10">
        <el-col v-if="formTitle === '创建智能柜'" :span="6" class="stationSelectCol">
          <el-row>
            <button class="newStationButton" @click="createStation">新 建 站 点</button>
            <el-table
              ref="stationRef"
              :data="stationTableAry"
              size="mini"
              height="350px"
              border
              stripe
              highlight-current-row
              @current-change="afterOpen"
            >
              <el-table-column label="选择已有站点" align="center" width="200">
                <el-table-column label="编号" prop="stationCode" align="center" width="50" :show-overflow-tooltip="true" />
                <el-table-column label="站点名称" prop="stationName" align="center" widtn="150" :show-overflow-tooltip="true" />
              </el-table-column>
            </el-table>
          </el-row>
          <el-row type="flex" justify="center">
            <el-pagination small layout="prev, pager, next" :total="stationTotal" @current-change="handleStationCurrentChange" />
          </el-row>
        </el-col>
        <el-col :span="9">
          <el-form ref="form1" :rules="rules1" :model="form1" label-width="170px">
            <el-form-item label="站点编号" prop="stationCode">
              <el-input v-model="form1.stationCode" :disabled="disabled" />
            </el-form-item>
            <el-form-item label="站点名称" prop="stationName">
              <el-input v-model="form1.stationName" :disabled="disabled" />
            </el-form-item>
            <el-form-item label="设备类型" prop="stationName">
              <el-select v-model="form1.type" placeholder="请选择" :disabled="disabled" >
                <el-option
                  v-for="item in type"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="门禁关闭时间(s)" prop="autoCloseDoorSpan" v-if="form1.type=='room'">
              <el-input v-model="form1.autoCloseDoorSpan" :disabled="disabled" />
            </el-form-item>
            <el-form-item label="开门报警时长(s)" prop="doorOpenAlertSpan">
              <el-input v-model="form1.doorOpenAlertSpan" :disabled="disabled" />
            </el-form-item>
            <el-form-item label="自动登出时长(s)" prop="autoLogoutSpan">
              <el-input v-model="form1.autoLogoutSpan" :disabled="disabled" />
            </el-form-item>
            <el-form-item label="自动上传数据时长(s)" prop="autoUploadSpan">
              <el-input v-model="form1.autoUploadSpan" :disabled="disabled" />
            </el-form-item>
            <el-form-item label="自动下载数据时长(s)" prop="autoDownloadSpan">
              <el-input v-model="form1.autoDownloadSpan" :disabled="disabled" />
            </el-form-item>
            <el-form-item label="灯光时长(s)" prop="lampCloseSpan">
              <el-input v-model="form1.lampCloseSpan" :disabled="disabled" />
            </el-form-item>
            <el-form-item label="扫描时间(s)" prop="scanTime">
              <el-input v-model="form1.scanTime" :disabled="disabled" />
            </el-form-item>
            <el-form-item label="工号长度" prop="jobNumberMax">
              <el-input v-model="form1.jobNumberMax" :disabled="disabled" />
            </el-form-item>
            <el-form-item label="密码长度" prop="passwordMax">
              <el-input v-model="form1.passwordMax" :disabled="disabled" />
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="9">
          <el-form ref="form2" :rules="rules2" :model="form2" label-width="120px">
            <el-form-item label="站点说明" prop="remark">
              <el-input v-model="form2.remark" type="textarea" :disabled="disabled" :autosize="{ minRows:4, maxRows: 6}" />
            </el-form-item>
            <el-form-item label="站点已设柜号" prop="hasChest">
              <span v-for="item in form2.hasChest" :key="item" class="hasChestSpan">{{ item }}</span>
            </el-form-item>
            <el-form-item v-if="formTitle === '创建智能柜' || formTitle === '编辑智能柜'" label="智能柜号" prop="chestNo">
              <el-input v-model="form2.chestNo" />
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <el-divider />
      <el-row>
        <div class="formButtonDiv">
          <el-button size="mini" class="formButton" @click="closeFormDialog">取 消</el-button>
          <el-button type="primary" size="mini" class="formButton" @click="submit">提 交</el-button>
        </div>
      </el-row>
    </el-dialog>
    <!-- 配置对话框 -->
    <el-dialog :visible.sync="configDialogVisible" width="50%" top="5vh" :close-on-click-modal="false" @close="closeConfigDialog">
      <ConfigPage
        v-if="configDialogVisible"
        :in-extra-form="extraForm"
        :in-config-target="configTarget"
        :in-config-ary="configAry"
        @submitConfig="submitConfig"
        @closeConfigPage="closeConfigDialog"
      />
      <!-- v-if="configDialogVisible" 做到创建销毁组件，可以在组件中使用生命周期钩子 -->
    </el-dialog>
  </div>
</template>

<script>
import ConfigPage from '@/components/fsd/ConfigPage'
import { createStationAndChestAPI, getChestsByStationAPI, editStationAPI, createChestAPI, getStationByChestAPI, changeStationAndChestNoByChestAPI, editChestAPI  } from '@/util/back_front_api/chests.js'
import { getUsersAllAPI } from '@/util/back_front_api/users.js'
import { changeUsersByChestAPI, getUsersByChestAPI } from '@/util/back_front_api/chests_users.js'
import { getChestGroupsAllAPI } from '@/util/back_front_api/chestGroups.js'
import { changeChestGroupsByChestAPI, getChestGroupsByChestAPI } from '@/util/back_front_api/chests_chestGroups.js'
import { getStationsAPI, getStationsAllAPI, updateClientAPI } from '@/util/back_front_api/stations.js'

export default {
  name: 'fsdchest',
  components: {
    ConfigPage
  },
  data() {
    let validateINT = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('该项不能为空'))
      } else {
        value = parseFloat(value)
        if (Number.isInteger(value)) {
          if (value <= 0) {
            callback(new Error('该项值必须大于零'))
          } else {
            callback()
          }
        } else {
          callback(new Error('该项值必须是整数'))
        }
      }
    }
    let validateINTAuto = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('该项不能为空'))
      } else {
        value = parseFloat(value)
        if (Number.isInteger(value)) {
          if (value < 20) {
            callback(new Error('该项值必须大于等于20'))
          } else {
            callback()
          }
        } else {
          callback(new Error('该项值必须是整数'))
        }
      }
    }
    let checkScanTime = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('该项不能为空'))
      } else {
        value = parseFloat(value)
        if (Number.isInteger(value)) {
          if (value < 2 || value > 30) {
            callback(new Error('该项值必须介于2-30之间'))
          } else {
            callback()
          }
        } else {
          callback(new Error('该项值必须是整数'))
        }
      }
    }
    let lampCloseSpan = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('该项不能为空'))
      } else {
        value = parseFloat(value)
        if (Number.isInteger(value)) {
          if (value < 10) {
            callback(new Error('该项值必须大于等于10'))
          } else {
            callback()
          }
        } else {
          callback(new Error('该项值必须是整数'))
        }
      }
    }
    let validateChestNo = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入智能柜序号'))
      } else {
        value = parseFloat(value)
        if (Number.isInteger(value)) {
          if (value <= 0) {
            callback(new Error('时长值必须大于零'))
          } else {
            this.form2.hasChest.forEach((item, index, ary) => {
              ary[index] = parseFloat(item)
            })
            for (let i = 0; i < this.form2.hasChest.length; i += 1) {
              if (this.form2.hasChest[i] === value) {
                callback(new Error('该智能柜序号已存在'))
                break
              }
            }
            callback()
          }
        } else {
          callback(new Error('智能柜序号必须是整数'))
        }
      }
    }
    return {
      searchDisabled: false,
      searchWord: '请输入关键词...',
      // 列表
      stationTableAry: [],
      chestsByStationAry: [],
      // 折叠
      activeNames: 'stationTable',
      idFromStationTable: '',
      chestTableDisable: true,
      stationTableDisable: true,
      stationTableTitle: '站点管理',
      chestTableTitle: '',
      // 页条
      // 表单对话框
      formTitle: '',
      disabled: false,
      formDialogVisible: false,
      form1: {
        stationCode: '',
        type: '',
        stationName: '',
        autoCloseDoorSpan: '',
        doorOpenAlertSpan: '',
        autoLogoutSpan: '',
        autoUploadSpan: '',
        autoDownloadSpan: '',
        lampCloseSpan: '30',
        scanTime: '6',
        jobNumberMax: '4',
        passwordMax: '6'
      },
      form2: {
        remark: '',
        hasChest: [],
        chestNo: ''
      },
      rules1: {
        stationCode: [
          { required: true, trigger: 'blur' }
        ],
        stationName: [
          { required: true, message: '请输入站点名称', trigger: 'blur' }
        ],
        autoCloseDoorSpan: [
          { required: true, validator: lampCloseSpan, trigger: 'blur' }
        ],
        doorOpenAlertSpan: [
          { required: true, validator: validateINTAuto, trigger: 'blur' }
        ],
        autoLogoutSpan: [
          { required: true, validator: validateINTAuto, trigger: 'blur' }
        ],
        autoUploadSpan: [
          { required: true, validator: validateINTAuto, trigger: 'blur' }
        ],
        autoDownloadSpan: [
          { required: true, validator: validateINTAuto, trigger: 'blur' }
        ],
        lampCloseSpan: [
          { required: true, validator: lampCloseSpan, trigger: 'blur' }
        ],
        scanTime: [
          { required: true, validator: checkScanTime, trigger: 'blur' }
        ],
        jobNumberMax: [
          { required: true, validator: validateINT, trigger: 'blur' }
        ],
        passwordMax: [
          { required: true, validator: validateINT, trigger: 'blur' }
        ]
      },
      rules2: {
        chestNo: [
          { required: true, validator: validateChestNo, trigger: 'blur' }
        ]
      },
      stationTotal: 0,
      // 配置对话框
      configDialogVisible: false,
      configTarget: {
        id: '',
        dialogTitle: '',
        itemTitle: '',
        name: '',
        type: ''
      },
      configAry: [],
      extraForm: {
        title: '',
        formItem: []
      },
      // 请求
      getStationsReq: {
        keyword: '',
        currentPage: 1,
        pageSize: 10
      },
      createChestReq: {
        chestNo: '',
        stationId: ''
      },
      createStationAndChestReq: {
        stationCode: '',
        stationName: '',
        type: '',
        autoCloseDoorSpan: '',
        doorOpenAlertSpan: '',
        autoLogoutSpan: '',
        autoUploadSpan: '',
        autoDownloadSpan: '',
        remark: '',
        chestNo: '',
        lampCloseSpan: '',
        scanTime: '',
        jobNumberMax: '',
        passwordMax: ''
      },
      getByStationReq: {
        id: ''
      },
      getByChestReq: {
        id: ''
      },
      changeReq: {
        id: '',
        idAry: []
      },
      changeStationAndChestNoReq: {
        chestId: '',
        stationId: '',
        chestNo: ''
      },
      editStationReq: {
        id: '',
        stationCode: '',
        stationName: '',
        type: '',
        autoCloseDoorSpan: '',
        doorOpenAlertSpan: '',
        autoLogoutSpan: '',
        autoUploadSpan: '',
        autoDownloadSpan: '',
        lampCloseSpan: '',
        scanTime: '',
        remark: '',
        jobNumberMax: '',
        passwordMax: ''
      },
      editChestReq: {
        id: '',
        chestNo: ''
      },
      type: [{
        value: 'chest',
        label: '智能柜'
      }, {
        value: 'room',
        label: '智能屋'
      }]
    }
  },
  created() { // 使用keepalive后不能刷新的情况，在activated中获取list
    this.getStations()
    this.form1.type = this.type[0].value
  },
  methods: {
    formatOnlineStatus(row, column, cellValue, index) {
      return row.onlineStatus == 1 ? '在线' : '离线'
    },
    // 功能条
    clearKeyword() {
      this.getStationReq.keyword = ''
      this.getStations()
    },
    search() {
      this.getStationsReq.currentPage = 1
      this.getStations()
    },
    // 列表
    toChestTable(row) {
      if (!row) {
        return
      }
      this.getByStationReq.id = row.id
      this.getChestsByStation().then(() => {
        if (this.chestsByStationAry === []) {
          return
        }
        this.searchWord = ''
        this.searchDisabled = true
        this.activeNames = 'chestTable'
        this.stationTableDisable = false
        this.stationTableTitle = '站点管理'
        this.chestTableTitle = row.stationName + '中的智能柜管理'
      }).catch((err) => {
        console.log(err)
      })
    },
    toUpdate(row) {
      if (!row) {
        return
      }
      return updateClientAPI({stationCode: row.stationCode}).then(result => {
      }).catch(err => {
        console.log(err)
      })
    },
    expandStationTable(row) {
      let chestsByStationAryTemp = []
      this.getByStationReq.id = row.id
      getChestsByStationAPI(this.getByStationReq).then((result) => {
        chestsByStationAryTemp = result.data
        row.hasChestNum = chestsByStationAryTemp.length
      }).catch((err) => {
        console.log(err)
      })
    },
    async expandChestTable(row) {
      let usersTemp = []
      let chestGroupsTemp = []
      row.hasUsers = ''
      row.hasChestGroups = ''
      this.getByChestReq.id = row.id
      try {
        usersTemp = (await getUsersByChestAPI(this.getByChestReq)).data
        chestGroupsTemp = (await getChestGroupsByChestAPI(this.getByChestReq)).data
      } catch (err) {
        console.log(err)
      }
      usersTemp.forEach((user) => {
        if (row.hasUsers === '') {
          row.hasUsers = user.users.userName + '(' + user.users.jobNumber + ')'
        } else {
          row.hasUsers = row.hasUsers + '、' + user.users.userName + '(' + user.users.jobNumber + ')'
        }
      })
      chestGroupsTemp.forEach((chestGroup) => {
        if (row.hasChestGroups === '') {
          row.hasChestGroups = chestGroup.chestGroups.chestGroupName
        } else {
          row.hasChestGroups = row.hasChestGroups + '、' + chestGroup.chestGroups.chestGroupName
        }
      })
      if (row.hasUsers === '') {
        row.hasUsers = '（无）'
      }
      if (row.hasChestGroups === '') {
        row.hasChestGroups = '（无）'
      }
    },
    // 页条
    handleStationCurrentChange(page) {
      this.getStationsReq.currentPage = page
      this.getStations()
    },
    handleStationSizeChange(size) {
      this.getStationsReq.pageSize = size
      this.getStations()
    },
    // 折叠
    collapseChange() {
      if (this.activeNames === 'stationTable') {
        this.searchWord = '请输入关键词...'
        this.searchDisabled = false
        this.stationTableTitle = '站点管理'
        this.stationTableDisable = true
        this.chestTableTitle = ''
      }
    },
    // 表单对话框
    openCreateFormDialog() {
      this.formDialogVisible = true
      this.disabled = true
      this.form1.type = this.type[0].value
      this.$nextTick(() => {
        this.formTitle = '创建智能柜'
        this.$refs.form1.resetFields()
        this.$refs.form2.resetFields()
        this.form2.chestNo = '' // 由于v-if所以resetFields方法无效，单独清空
      })
    },
    openEditStationFormDialog(row) {
      this.formDialogVisible = true
      this.disabled = true

      this.$nextTick(() => {
        this.formTitle = '编辑站点'
        this.$refs.form1.resetFields()
        this.$refs.form2.resetFields()

        this.afterOpen(row)
      })
    },
    openEditChestFormDialog(row) {
      this.formDialogVisible = true
      this.disabled = true
      this.$nextTick(() => {
        this.formTitle = '编辑智能柜'
        this.$refs.form1.resetFields()
        this.$refs.form2.resetFields()
        this.form2.chestNo = '' // 由于v-if所以resetFields方法无效，单独清空

        this.editChestReq.id = row.id
        this.getByChestReq.id = row.id
        getStationByChestAPI(this.getByChestReq).then((result) => {
          this.afterOpen(result.data[0].stations)
        }).catch((err) => {
          this.utilMessage.warning(err.msg)
        })
      })
    },
    createStation() {
      this.$nextTick(() => {
        this.$refs.form1.resetFields()
        this.$refs.form2.resetFields()
        this.form2.chestNo = '' // 由于v-if所以resetFields方法无效，单独清空
        this.disabled = false
      })
    },
    afterOpen(station) {
      if (!station) {
        return
      }
      if (this.formTitle === '编辑站点') {
        this.disabled = false
      } else if (this.formTitle === '创建智能柜') {
        this.disabled = true
      } else if (this.formTitle === '编辑智能柜') {
        this.disabled = true
      } else {
        this.utilMessage.warning('formTitle有误。')
        return
      }
      let chestsByStationAryTemp = []
      this.form2.hasChest = []
      this.getByStationReq.id = station.id
      getChestsByStationAPI(this.getByStationReq).then((result) => {
        chestsByStationAryTemp = result.data
        this.$nextTick(() => {
          this.$refs.form1.resetFields()
          this.$refs.form2.resetFields()

          this.createChestReq.stationId = station.id

          this.editStationReq.id = station.id

          this.form1.stationCode = station.stationCode
          this.form1.stationName = station.stationName
          this.form1.type = station.type
          this.form1.autoCloseDoorSpan = station.autoCloseDoorSpan
          this.form1.doorOpenAlertSpan = station.doorOpenAlertSpan
          this.form1.autoLogoutSpan = station.autoLogoutSpan
          this.form1.autoUploadSpan = station.autoUploadSpan
          this.form1.autoDownloadSpan = station.autoDownloadSpan
          this.form1.lampCloseSpan = station.lampCloseSpan
          this.form1.scanTime = station.scanTime
          this.form1.jobNumberMax = station.jobNumberMax
          this.form1.passwordMax = station.passwordMax
          this.form2.remark = station.remark
          chestsByStationAryTemp.forEach((item) => {
            this.form2.hasChest.push(item.chestNo)
          })
        })
        if (this.formTitle === '创建智能柜') {
          this.$refs.stationRef.setCurrentRow()
        }
      }).catch((err) => {
        this.utilMessage.warning(err.msg)
      })
    },
    create() {
      this.$refs.form1.validate((valid) => {
        if (valid) {
          this.$refs.form2.validate((valid) => {
            if (valid) {
              this.$confirm('将会创建你所设置的主站或智能柜, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                if (this.disabled) {
                  this.createChestReq.chestNo = this.form2.chestNo
                  createChestAPI(this.createChestReq).then(res => {
                    this.utilMessage.success(res.msg)
                    setTimeout(() => {
                      this.getStations()
                    }, 500)
                  }).catch(err => {
                    console.log(err)
                  })
                  this.closeFormDialog()
                } else {
                  this.createStationAndChestReq.stationCode = this.form1.stationCode
                  this.createStationAndChestReq.stationName = this.form1.stationName
                  this.createStationAndChestReq.type = this.form1.type
                  this.createStationAndChestReq.autoCloseDoorSpan = this.form1.autoCloseDoorSpan
                  this.createStationAndChestReq.doorOpenAlertSpan = this.form1.doorOpenAlertSpan
                  this.createStationAndChestReq.autoLogoutSpan = this.form1.autoLogoutSpan
                  this.createStationAndChestReq.autoUploadSpan = this.form1.autoUploadSpan
                  this.createStationAndChestReq.autoDownloadSpan = this.form1.autoDownloadSpan
                  this.createStationAndChestReq.lampCloseSpan = this.form1.lampCloseSpan
                  this.createStationAndChestReq.scanTime = this.form1.scanTime
                  this.createStationAndChestReq.jobNumberMax = this.form1.jobNumberMax
                  this.createStationAndChestReq.passwordMax = this.form1.passwordMax
                  this.createStationAndChestReq.remark = this.form2.remark
                  this.createStationAndChestReq.chestNo = this.form2.chestNo
                  createStationAndChestAPI(this.createStationAndChestReq).then(res => {
                    this.utilMessage.success(res.msg)
                    setTimeout(() => {
                      this.getStations()
                    }, 500)
                  }).catch(err => {
                    console.log(err)
                  })
                  this.closeFormDialog()
                }
              }).catch(() => {
                return false
              })
            } else {
              console.log('error submit!!')
              this.utilMessage.warning('请正确输入信息。')
              return false
            }
          })
        } else {
          console.log('error submit!!')
          this.utilMessage.warning('请正确输入信息。')
          return false
        }
      })
    },
    editStation() {
      this.$refs.form1.validate((valid) => {
        if (valid) {
          this.$confirm('将会修改你所选的站点的信息, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.editStationReq.stationCode = this.form1.stationCode
            this.editStationReq.stationName = this.form1.stationName
            this.editStationReq.type = this.form1.type
            this.editStationReq.autoCloseDoorSpan = this.form1.autoCloseDoorSpan
            this.editStationReq.doorOpenAlertSpan = this.form1.doorOpenAlertSpan
            this.editStationReq.autoLogoutSpan = this.form1.autoLogoutSpan
            this.editStationReq.autoUploadSpan = this.form1.autoUploadSpan
            this.editStationReq.autoDownloadSpan = this.form1.autoDownloadSpan
            this.editStationReq.lampCloseSpan = this.form1.lampCloseSpan
            this.editStationReq.scanTime = this.form1.scanTime
            this.editStationReq.jobNumberMax = this.form1.jobNumberMax
            this.editStationReq.passwordMax = this.form1.passwordMax
            this.editStationReq.remark = this.form2.remark
            editStationAPI(this.editStationReq).then(res => {
              this.utilMessage.success(res.msg)
              setTimeout(() => {
                this.getStations()
              }, 500)
            }).catch(err => {
              console.log(err)
            })
            this.closeFormDialog()
          }).catch(() => {
            return false
          })
        } else {
          console.log('error submit!!')
          this.utilMessage.warning('请正确输入信息。')
          return false
        }
      })
    },
    editChest() {
      this.$refs.form2.validate((valid) => {
        if (valid) {
          this.$confirm('将会修改你所选的站点的信息, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.editChestReq.chestNo = this.form2.chestNo
            editChestAPI(this.editChestReq).then(res => {
              this.utilMessage.success(res.msg)
              setTimeout(() => {
                this.getChestsByStation()
              }, 500)
            }).catch(err => {
              console.log(err)
            })
            this.closeFormDialog()
          })
        } else {
          console.log('error submit!!')
          this.utilMessage.warning('请正确输入信息。')
          return false
        }
      })
    },
    submit() {
      if (this.formTitle === '创建智能柜') {
        this.create()
      } else if (this.formTitle === '编辑智能柜') {
        this.editChest()
      } else if (this.formTitle === '编辑站点') {
        this.editStation()
      } else {
        this.utilMessage.warning('formTitle有误。')
      }
    },
    closeFormDialog() {
      this.formTitle = ''
      this.formDialogVisible = false
    },
    // 配置对话框
    async setUsers(row) {
      this.configAry = [] // configTarget赋值
      this.configTarget.dialogTitle = '分配具备该智能柜使用权的用户'
      this.configTarget.itemTitle = '请选择用户：'
      this.configTarget.name = row.chestNo
      this.configTarget.id = row.id
      this.configTarget.type = 'checkbox'

      let usersAll = [] // configAry赋值
      let usersByChest = []
      this.getByChestReq.id = row.id
      try {
        usersAll = (await getUsersAllAPI()).data
        usersByChest = (await getUsersByChestAPI(this.getByChestReq)).data
      } catch (err) {
        console.log(err)
      }
      let obj = {}
      let i
      obj.id = '0'
      obj.checkItem = []
      obj.title = ''
      usersAll.forEach((userInUsersAll) => {
        let objItem = {}
        objItem.id = userInUsersAll.id
        objItem.display = userInUsersAll.userName + '(' + userInUsersAll.jobNumber + ')'
        objItem.col = 6
        objItem.checked = false
        for (i = 0; i < usersByChest.length; i += 1) {
          if (userInUsersAll.id === usersByChest[i].userId) {
            objItem.checked = true
            usersByChest.splice(i, 1)
            break
          }
        }
        obj.checkItem.push(objItem)
      })
      this.configAry.push(obj)

      this.configDialogVisible = true
    },
    async setChestGroups(row) {
      this.configAry = [] // configTarget赋值
      this.configTarget.dialogTitle = '分配该智能柜所属的智能柜组'
      this.configTarget.itemTitle = '请选择智能柜组：'
      this.configTarget.name = row.chestNo
      this.configTarget.id = row.id
      this.configTarget.type = 'checkbox'

      let chestGroupsAll = [] // configAry赋值
      let chestGroupsByChest = []
      this.getByChestReq.id = row.id
      try {
        chestGroupsAll = (await getChestGroupsAllAPI()).data
        chestGroupsByChest = (await getChestGroupsByChestAPI(this.getByChestReq)).data
      } catch (err) {
        console.log(err)
      }
      let obj = {}
      let i
      obj.id = '0'
      obj.checkItem = []
      obj.title = ''
      chestGroupsAll.forEach((chestGroupInChestGroupsAll) => {
        let objItem = {}
        objItem.id = chestGroupInChestGroupsAll.id
        objItem.display = chestGroupInChestGroupsAll.chestGroupName
        objItem.col = 6
        objItem.checked = false
        for (i = 0; i < chestGroupsByChest.length; i += 1) {
          if (chestGroupInChestGroupsAll.id === chestGroupsByChest[i].chestGroupId) {
            objItem.checked = true
            chestGroupsByChest.splice(i, 1)
            break
          }
        }
        obj.checkItem.push(objItem)
      })
      this.configAry.push(obj)

      this.configDialogVisible = true
    },
    async setStations(row) {
      this.configAry = [] // configTarget赋值
      this.configTarget.dialogTitle = '分配该智能柜所属的站点'
      this.configTarget.itemTitle = '请选择站点：'
      this.configTarget.name = row.chestNo
      this.configTarget.id = row.id
      this.configTarget.type = 'radio'

      this.extraForm.title = '智能柜柜号修改表单'
      this.extraForm.formItem = [
        {
          name: '智能柜柜号',
          value: row.chestNo,
          validate: 'chestNo'
        }
      ]

      let stationsAll = [] // configAry赋值
      let stationByChest = []
      this.getByChestReq.id = row.id
      try {
        stationsAll = (await getStationsAllAPI()).data
        stationByChest = (await getStationByChestAPI(this.getByChestReq)).data
        console.log(2222)
      } catch (err) {
        console.log(err)
      }
      let obj = {}
      let i
      obj.id = '0'
      obj.checkItem = []
      obj.title = ''
      stationsAll.forEach((stationInStationsAll) => {
        let objItem = {}
        objItem.id = stationInStationsAll.id
        objItem.display = stationInStationsAll.stationName
        objItem.col = 6
        objItem.checked = false
        for (i = 0; i < stationByChest.length; i += 1) {
          if (stationInStationsAll.id === stationByChest[i].stationId) {
            objItem.checked = true
            stationByChest.splice(i, 1)
            break
          }
        }
        obj.checkItem.push(objItem)
      })
      this.configAry.push(obj)

      this.configDialogVisible = true
    },
    closeConfigDialog() {
      this.extraForm.title = ''
      this.extraForm.formItem = []
      this.configDialogVisible = false
    },
    async submitConfig(outObj) {
      let msg
      this.closeConfigDialog()

      if (outObj.title === '分配具备该智能柜使用权的用户') {
        this.changeReq.id = outObj.targetId
        this.changeReq.idAry = []

        outObj.configId.forEach((item) => {
          let tempObj = {}
          tempObj.chestId = outObj.targetId
          tempObj.userId = item
          this.changeReq.idAry.push(tempObj)
        })
        try {
          msg = (await changeUsersByChestAPI(this.changeReq)).msg
          this.utilMessage.success(msg)
        } catch (err) {
          console.log(err)
        }
      } else if (outObj.title === '分配该智能柜所属的智能柜组') {
        this.changeReq.id = outObj.targetId
        this.changeReq.idAry = []

        outObj.configId.forEach((item) => {
          let tempObj = {}
          tempObj.chestId = outObj.targetId
          tempObj.chestGroupId = item
          this.changeReq.idAry.push(tempObj)
        })
        try {
          msg = (await changeChestGroupsByChestAPI(this.changeReq)).msg
          this.utilMessage.success(msg)
        } catch (err) {
          console.log(err)
        }
      } else if (outObj.title === '分配该智能柜所属的站点') {
        console.log('outObj', outObj)
        this.changeStationAndChestNoReq.chestId = outObj.targetId
        this.changeStationAndChestNoReq.stationId = outObj.configId[0]
        this.changeStationAndChestNoReq.chestNo = outObj.extraForm['智能柜柜号']

        try {
          msg = (await changeStationAndChestNoByChestAPI(this.changeStationAndChestNoReq)).msg
          this.utilMessage.success(msg)
          setTimeout(() => {
            this.getChestsByStation()
          }, 500)
        } catch (err) {
          console.log(err)
        }
      } else {
        this.utilMessage.warning('提交配置种类出错')
      }
    },
    // 请求
    getStations() {
      let index
      getStationsAPI(this.getStationsReq).then(result => {
        index = ((this.getStationsReq.currentPage - 1) >= 0 ? (this.getStationsReq.currentPage - 1) : 0) * this.getStationsReq.pageSize
        this.stationTotal = result.data.count
        this.stationTableAry = result.data.rows.map((item) => {
          this.$set(item, 'index', index += 1)
          this.$set(item, 'hasChestNum', '')
          return item
        })
      }).catch(err => {
        console.log(err)
      })
    },
    getChestsByStation() {
      this.chestsByStationAry = []
      return getChestsByStationAPI(this.getByStationReq).then(result => {
        this.chestsByStationAry = result.data.map((item) => {
          this.$set(item, 'hasChestGroups', '')
          this.$set(item, 'hasUsers', '')
          return item
        })
      }).catch(err => {
        console.log(err)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.buttonRow{
  margin: 10px;
}
.collapse{
  margin: 10px;
}
.collapseItem >>> .el-collapse-item__header{
  color: #409EFF;
}
.tableDiv {
  height: 400px;
  overflow-y: scroll;
}
.pageRow{
  margin: 5px 0px 0px 0px;
}
.table-expand {
  font-size: 0;
}
.table-expand label {
  width: 90px;
  color: #99a9bf;
}
.table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 100%;
}
.switchDiv {
}
.switch {
  margin: 0px 10px 0px 0px;
}
.switchText {
  display: inline-block;
}
.formTitle {
  text-align: center;
  letter-spacing: 10px;
  font-size: 20px;
}
.formRow {
  padding: 0px 100px 0px 100px;
}
.formButtonDiv {
  text-align: center;
}
.formButton {
  margin: 0px 30px 0px 30px;
}
.el-table th.gutter {
  display: table-cell !important
}
.newStationButton{
  width: 100%;
  background-color: #409EFF;
  border: none;
  outline: none; // 去除点击后的边框 input button都适用
  color: white;
  font-size: 12px;
  padding: 5px;
  border-radius: 0px;
  margin: 0px 0px 5px 0px;
  border-radius: 2px;
  cursor: pointer;
}
.newStationButton:active {
  background-color: #8cc6ff;
  border: none;
}
.hasChestSpan{
  margin: 0px 10px 0px 0px;
}
// 滚动条修改
::-webkit-scrollbar {
  width:3px;
}
::-webkit-scrollbar-thumb{
  background: #bcddff;
  border-radius: 5px;
}
</style>
